import { useConfig } from "../../hook/D8dConfigProvider.tsx";
import { useApiRequest } from "../../hook/useApiRequest.ts";
import type { TPageRequest } from "../../global.ts";
import { Form, Select } from "antd";
import { useEffect, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";

interface FieldIdentifier {
  label: string;
  value: string;
}

interface SelectOption {
  label: string;
  value: any;
}

interface Props {
  listApiUrl?: string; // 树列表API
  fieldIdentifier?: FieldIdentifier; // 字段标识
  value?: any;
  onChange?: (values: any) => void;
  multiple?: boolean;
  pageSize?: number; // 新增 pageSize 参数
  showSearch?: boolean; // 新增 showSearch 属性
  formFilterFields?: Record<string, string>; // 修改为对象类型
  onFiltersChange?: (filters: Record<string, any>) => Record<string, any>; // 修改回调函数的返回类型
  queryKey?: string; // 新增：自定义 queryKey
  enabled?: boolean; // 新增：控制查询是否启用
}

export default function AdminSelect({
  value,
  onChange,
  listApiUrl,
  fieldIdentifier,
  multiple = false,
  pageSize = 50, // 设置默认值为 50
  showSearch = false, // 设置 showSearch 的默认值为 false
  formFilterFields,
  onFiltersChange,
  queryKey,
  enabled = true,
}: Props) {
  const { token } = useConfig();
  const { requestWithToken } = useApiRequest();
  const form = Form.useFormInstance();

  // 监听表单字段变化
  const watchedValues: Record<string, any> = {};
  if (formFilterFields) {
    Object.keys(formFilterFields).forEach(key => {
      watchedValues[key] = Form.useWatch(key, form);
    });
  }

  // 使用 useMemo 创建过滤值对象
  const filterValues = useMemo(() => {
    return watchedValues;
  }, [watchedValues]);

  // 检查过滤条件是否都已选择
  const [allFiltersSelected, firstMissingFilter] = useMemo(() => {
    if (!formFilterFields) return [true, null];
    let missing: string | null = null;
    const allSelected = Object.keys(formFilterFields).every(key => {
      if (filterValues[key] === undefined || filterValues[key] === null) {
        if (!missing) missing = key;
        return false;
      }
      return true;
    });
    return [allSelected, missing];
  }, [formFilterFields, filterValues]);

  // 构建查询参数
  const buildQueryParams = () => {
    let filters: Record<string, any> = {};
    if (formFilterFields) {
      Object.entries(formFilterFields).forEach(([formField, filterField]) => {
        if (filterValues[formField] !== undefined) {
          filters[filterField] = { $eq: filterValues[formField] };
        }
      });
    }

    if (onFiltersChange) {
      filters = onFiltersChange(filters);
    }

    return {
      sort: ["updated_at:desc"],
      pagination: { page: 1, pageSize },
      filters,
    } as TPageRequest;
  };

  // 使用 React Query 获取数据
  const { data: asyncData = [] } = useQuery({
    queryKey: [queryKey || 'adminSelect', listApiUrl, filterValues],
    queryFn: async () => {
      if (!listApiUrl || !token || !allFiltersSelected) {
        return [];
      }

      try {
        const result = await requestWithToken({
          url: listApiUrl,
          method: "GET",
          data: buildQueryParams(),
        });

        if ((result?.code === 200 || result?.success) && fieldIdentifier) {
          return result.data.map(
            (item: any) => ({
              label: item[fieldIdentifier?.label],
              value: item[fieldIdentifier?.value],
            })
          );
        }
        return [];
      } catch (error) {
        console.error('AdminSelect data fetch error:', error);
        return [];
      }
    },
    enabled: enabled && !!listApiUrl && !!token && allFiltersSelected,
    staleTime: 1000 * 60 * 5, // 5分钟的缓存时间
    gcTime: 1000 * 60 * 10, // 10分钟的垃圾回收时间
  });

  return (
    <Select
      placeholder={allFiltersSelected ? "请选择" : `请先选择${firstMissingFilter}`}
      value={allFiltersSelected ? value : undefined}
      options={asyncData}
      onChange={onChange}
      allowClear
      mode={multiple ? "multiple" : undefined}
      showSearch={showSearch} // 添加 showSearch 属性
      filterOption={(input, option) =>
        (option?.label?.toString().toLowerCase() ?? '').includes(input.toLowerCase())
      } // 添加过滤选项的逻辑
      disabled={!allFiltersSelected}
    />
  );
}
